import { ICellEditor } from './types';
import { Cell } from '../cors/cell';
import './editor.base.less';
import { NPluginManage } from '../types/cors';
import { IValueChangePlugin } from '../pugins/value-change.plugin.interface';
export abstract class EditorBase implements ICellEditor {
  protected currentValue: string = '';
  protected abstract  pluginManage: NPluginManage.IPluginManage;
  protected cell: Cell<any>;
  protected valueChangePlugin: IValueChangePlugin;
  constructor() {

  }
  public initEditor(cell: Cell<any>, container: HTMLElement, finishCallBack: () => void, event: {preventDefault:boolean}): void {
    this.valueChangePlugin = this.pluginManage.getPlugin('ValueChangePlugin') as any; 
    this.cell = cell;
    let editorSize = {
      w: container.clientWidth,
      h: container.clientHeight
    }
    let textEle = document.createElement('textarea');
    textEle.setAttribute('class', 'z-text-editor');
    textEle.setAttribute('style', `
      height: ${editorSize.h - 4}px;
      width: ${editorSize.w - 4}px;
    `);
    this.currentValue = cell.value.getOriginValue() ? cell.value.getOriginValue().toString() : null;
    container.append(textEle)
    textEle.value = this.currentValue;
    textEle.focus();
    textEle.addEventListener('keydown', (evt: KeyboardEvent) => {
      if(evt.altKey && evt.code === 'Enter') {
        textEle.value = textEle.value + '\n';
        this.currentValue = textEle.value;
        setTimeout(() => {
          textEle.focus();
        }, 300);
      }
      if(!evt.altKey && evt.code === 'Enter') {
        this.valueChangePlugin.updateCellValue(this.cell.position.row, this.cell.position.col, this.currentValue);
        finishCallBack();
      }
    });
    textEle.addEventListener('input', (evt: any) => {
      this.currentValue = evt.target.value;
    });
  }
  public finish(): void {
    this.valueChangePlugin.updateCellValue(this.cell.position.row, this.cell.position.col, this.currentValue);
  }
}